import { getSetting,openSetting,chooseAddress,showModal,showToast } from "../../utils/asyncWx.js";
import regeneratorRuntime from '../../lib/runtime/runtime';

// pages/cart/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address:{},
    cart:[],
    allChecked:false,
    totalPrice:0,
    totalNum:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  //获取用户收货地址
  async handleChooseAddress(){
    
    //获取权限状态
  //  wx.getSetting({
  //    success: (result) => {
  //      const scopeAddress = result.authSetting["scope.address"];
  //      if(scopeAddress === true || scopeAddress === undefined){
  //        wx.chooseAddress({
  //          success: (result1) => {
  //            console.log(result1);
  //          }
  //        });
           
  //      }else{
  //        //用户拒绝权限
  //        wx.openSetting({
  //          success: (result2) => {
  //           wx.chooseAddress({
  //             success: (result3) => {
  //               console.log(result3);
  //             }
  //          })
  //          }
  //        });
           
  //      }
  //    }
  //  });
    
   try{
    //获取权限状态
    const res1 = await getSetting();
    const scopeAddress = res1.authSetting["scope.address"];
    //判断权限状态
    if(scopeAddress === false){
       //诱导客户打开权限页面
       await openSetting();
     }
     
    //获取地址的api
    const address = await chooseAddress();
    //存入到缓存中
    wx.setStorageSync("address", address);
      

   }catch(error){
    console.log(error);
   }
   
      
  },

 onShow(){
    //获取缓存中的数据
    const address = wx.getStorageSync("address");
    //获取缓存中的购物车数据
    const cart = wx.getStorageSync("cart") || [];
    // //计算全选
    // // const allChecked = cart.length?cart.every(v => v.checked):false;
    // let allChecked = true;
    // //总价格 总数量
    // let totalPrice = 0;
    // let totalNum = 0;
    // cart.forEach(v => {
    //   if(v.checked){
    //     totalPrice += v.num * v.goods_price;
    //     totalNum += v.num;
    //   }else{
    //     allChecked = false;
    //   }
    // });
    // //判断数组是否为空
    // allChecked = cart.length!=0?allChecked:false;
    // //给data赋值
    // this.setData({
    //   address,
    //   cart,
    //   allChecked,
    //   totalPrice,
    //   totalNum
    // })

    this.setData({
      address
    })
    this.setCart(cart);
      
  },

  //商品的选中
  handleItemChange(e){
    //获取被修改的商品id
    const goods_id = e.currentTarget.dataset.id;
    // console.log(goods_id);
    //获取购物车数组
    let {cart} = this.data;
    //找到被修改的索引
    let index = cart.findIndex(v => v.goods_id === goods_id);
    //选中状态取反
    cart[index].checked = !cart[index].checked;
    this.setCart(cart);
    
  },

  //设置购物车状态同时 重新计算数据 把重复代码拿出来
  setCart(cart){
    
    
    

    let allChecked = true;
    //总价格 总数量
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v => {
      if(v.checked){
        totalPrice += v.num * v.goods_price;
        totalNum += v.num;
      }else{
        allChecked = false;
      }
    });
    //判断数组是否为空
    allChecked = cart.length!=0?allChecked:false;


     
     this.setData({
      cart,
      totalPrice,
      totalNum,
      allChecked
    })

    wx.setStorageSync("cart",cart);
  },

  //商品的全选功能
  handleItemAllCheck(){
    //获取 data数据
    let {cart,allChecked} = this.data;
    //修改值
    allChecked = !allChecked;
    //循环修改cart数组中的商品选中状态
    cart.forEach(v => v.checked=allChecked);
    //修改后的值放回data中
    this.setCart(cart);

  },

  //编辑加减数量
  async handleItemNumEdit(e){
    //获取传递过来参数
    const {operation,id} = e.currentTarget.dataset;
    // console.log(operation,id);
    //获取购物车数组
    let {cart} = this.data;
    //找到需要修改商品的索引
    const index = cart.findIndex(v => v.goods_id===id);

    //判断是否要执行删除
    if(cart[index].num===1&&operation===-1){
      //弹窗提示
      const res = await showModal({content:'您是否要删除？'});
      if (res.confirm) {
        cart.splice(index,1);
        this.setCart(cart);
       }
    }else{
      //进行修改数量
      cart[index].num += operation;
      //设置数据回到缓存
      this.setCart(cart);
    }


    

  },

  //点击结算
  async handlePay(){
    //判断收货地址
    const {address,totalNum} = this.data;
    if(!address.userName){
      await showToast({title:"您还没有选择收货地址"});
      return;
    }
    //判断用户是否选购商品
    if(totalNum === 0){
      await showToast({title:"您还没有选购商品"});
      return;
    }
    //跳转到支付页面
    wx.navigateTo({
      url: '/pages/pay/index',
    });
      
  }
  
})